#!/bin/bash

# THIS DRIVER WRITTEN BY MATTHEW VONA FOR THE RMYOUNG 81000 ULTRASONIC ANEMOMETER.
# THE PRINCIPLE OF OPERATION IS THAT THE DRIVER WILL SIT AND PASSIVELY AGGREGATE DATA
# INTO DATA FILES WHICH ARE THEN PROCESSED FOR INCLUSION INTO THE RAW DATARECORD.
# THE RATE OF DATA COLLECTION SHOULD BE INSIGNIFICANT. 
# THIS SCRIPT RERQUIRES A PARALLEL INGESTER BE USED TO STTISTICALLY DIGEST THE DATA AND RECORD IT IN THE 
# CARBLogger DATA RECORD. 
################################################################################################
#
# SET THE PORT AND CLEAR THE FIRST DATA PROCESSING FILE
#
################################################################################################
if !(stty -F $1 raw ispeed $2 ospeed $2 cs7 -parodd -ignpar -cstopb -echo); then
	{
		echo "Failed to initialize the serial port. Exiting"
		exit 1;

	}
fi
#GET the present location
DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# Begin the main loop
last_sec="90"
while [ 1 ]; 
do
    
    sec=`date '+%S'`
    if [ "$sec" -ne "$last_sec" ]
    then
	#stamp=`date '+%H %M %S %N' | tr -d '\n'`
	stamp=`date '+%H %M %S %N'`
	#hrbin=`echo $stamp | awk '{ print $1 }'`
	#hrbin="${stamp:0:2}"
	#minbin=`echo $stamp | awk '{ print $2 }'`
	#minbin="${stamp:3:2}"
	data=`dd if=${1} count=25 bs=1 cbs=25 conv=noerror,notrunc 2>/dev/null | grep -v '\^M'`
	#data=`sjinn -d ${1} -b$2 -p7e2 -s "send\r" -r23 -w0.6`
	record="${stamp} ${data}"
	#count=`echo ${record} | wc -w`
	#record="${count} ${record}"
	#MAKE A FOLDER FOR THE HOUR IF IT DOSEN'T EXIST	
	if [ ! -d "${DIR}/${stamp:0:2}" ]; then
		
		mkdir "${DIR}/${stamp:0:2}"
		
	fi
	#IF THE CHARS AT POSITION 32-36 match "RH T", WRITE OUT TO THE SECOND FILE
	#filter for malformed lines to avoid bad data
	if [ "${record:29:4}" = "RH T" ]
	then
	    echo "$record" >> "${DIR}/${stamp:0:2}/${stamp:3:2}.dat"
	    last_sec="$sec"
	else
	    echo "$record" >> "${DIR}/${stamp:0:2}/error.dat"
	    last_sec="$sec"
	fi	
	
    fi
    

done
